package com.zxl.live.tools.base;

import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;

import com.google.firebase.analytics.FirebaseAnalytics;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/30.
 */
public class ActivityLifecycle extends BaseActivityLifecycle {

    private static ActivityLifecycle sInstance;

    private Activity mCurrent;

    private Map<Activity, FirebaseAnalytics> mList;

    private ActivityLifecycle() {
        mList = new HashMap<>();
    }

    public static void registerActivityLifecycleCallbacks(Application application) {
        if (null == sInstance) {
            sInstance = new ActivityLifecycle();
            application.registerActivityLifecycleCallbacks(sInstance);
        }
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        super.onActivityCreated(activity, savedInstanceState);
        mCurrent = activity;
        mList.put(activity, FirebaseAnalytics.getInstance(activity));
    }

    @Override
    public void onActivityResumed(Activity activity) {
        super.onActivityResumed(activity);
        mCurrent = activity;
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        super.onActivityDestroyed(activity);
        mList.remove(activity);
    }

    public static Activity getActivity(Class cls) {
        if (null != sInstance) {
            if (sInstance.mCurrent != null) {
                return sInstance.mCurrent;
            }
        }
        return null;
    }

    public static FirebaseAnalytics getFirebaseAnalytics() {
        if (null != sInstance && sInstance.mCurrent != null) {
            return sInstance.mList.get(sInstance.mCurrent);
        }
        return null;
    }

    public static void killSelf() {
        if (null != sInstance) {
            if (!sInstance.mList.isEmpty()) {
                for (Activity activity : sInstance.mList.keySet()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        activity.finishAffinity();
                    } else {
                        activity.finish();
                    }
                }
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
